// 统一的API响应模型
class ApiResponse<T> {
  final int code;
  final String message;
  final T? data;

  ApiResponse({
    required this.code,
    required this.message,
    this.data,
  });

  // 从JSON解析响应
  factory ApiResponse.fromJson(
      Map<String, dynamic> json, T Function(Map<String, dynamic>) fromJsonT) {
    return ApiResponse<T>(
      code: json['code'] as int,
      message: json['message'] as String,
      data: json['data'] != null ? fromJsonT(json['data']) : null,
    );
  }

  // 从JSON解析列表响应
  factory ApiResponse.fromJsonList(
      Map<String, dynamic> json, T Function(Map<String, dynamic>) fromJsonT) {
    List<T> list = <T>[];
    if (json.containsKey('data') && json['data'] is List) {
      list = (json['data'] as List<dynamic>)
          .map((item) => fromJsonT(item as Map<String, dynamic>))
          .toList();
    }
    return ApiResponse(
      code: json['code'] as int,
      message: json['message'] as String,
      data: list as T,
    );
  }

  // 判断响应是否成功（code为0表示成功）
  bool get isSuccess => code == 0;

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'code': code,
      'message': message,
      'data': data,
    };
  }
}
